package com.kiwilss.aliyundemo.dylist

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.SurfaceTexture
import android.os.Bundle
import android.view.*
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.TextureView.SurfaceTextureListener
import android.view.View.OnTouchListener
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.aliyun.player.AliListPlayer
import com.aliyun.player.AliPlayerFactory
import com.aliyun.player.IPlayer
import com.aliyun.player.IPlayer.OnRenderingStartListener
import com.aliyun.player.nativeclass.PlayerConfig
import com.kiwilss.aliyundemo.GlobalConfig
import com.kiwilss.aliyundemo.R
import kotlinx.android.synthetic.main.activity_dy.*

/**
 * @author : Administrator
 * e-mail : kiwilss@163.com
 * time   : 2021/03/17
 *  desc   : AliListPlayer实现播放
 */
class DYListActivity : AppCompatActivity(R.layout.activity_dy) {

    val mAdapter by lazy { DyAdapter() }
    lateinit var mLayoutManager: ViewPagerLayoutManager

    var mInitPos: Int = 0//初始位置
    var mCurrentPosition = 0//当前位置
    var mIsPause: Boolean = false
    var mIsOnBackground: Boolean = false
    var isEnd: Boolean = false

    lateinit var mData: ArrayList<VideoInfoBean>
    lateinit var mVideoListPlayer: AliListPlayer

    lateinit var mGestureDetector: GestureDetector //手势监听

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mInitPos = intent.getIntExtra(GlobalConfig.POS, 0)
        mData = intent.getSerializableExtra(GlobalConfig.DATA) as ArrayList<VideoInfoBean>

        mLayoutManager = ViewPagerLayoutManager(this, LinearLayout.VERTICAL)

        rvDyList.run {
            layoutManager = mLayoutManager
            adapter = mAdapter
        }
        //初始化列表播放器
        initAliPlayer()
        //初始化播放界面和暂停/播放按钮
        initPlayerView()
        //监听滑动
        initListener()
        //处理数据
        initData()

    }

    private fun initData() {
        for (i in 0 until mData.size){
            mVideoListPlayer.addUrl(mData[i].videoUrl,i.toString())
        }
        rvDyList.scrollToPosition(mInitPos)
        mAdapter.setList(mData)
    }

    private fun initListener() {
        mLayoutManager.setOnViewPagerListener(object : OnViewPagerListener {
            override fun onInitComplete() {
                if (mInitPos != 0) {
                    mCurrentPosition = mInitPos
                } else {
                    val position = mLayoutManager.findFirstVisibleItemPosition()
                    if (position != -1) {
                        mCurrentPosition = position
                    }
                }
                startPlay(mCurrentPosition)
            }

            override fun onPageRelease(isNext: Boolean, position: Int) {
                //Log.i(TAG, "OnViewPager 释放位置:" + position + " mCurrentPosition=" + mCurrentPosition + " 下一页:" + isNext);
                if (mCurrentPosition == position) {
                    stopPlay()
                }
            }

            override fun onPageSelected(position: Int, isBottom: Boolean) {
                isEnd = isBottom
                if (mCurrentPosition != position) {
                    startPlay(position)
                } else {
                    //Log.i(TAG, "OnViewPager onPageSelected: 不做处理");
                }
                mCurrentPosition = position
            }
        })
    }

    /**
     * 播放视频
     */
    private fun startPlay(position: Int) {
        if (position < 0 || position >= mData.size) {
            return
        }
        //恢复界面状态
        mIsPause = false
        mPlayIconImageView.visibility = View.GONE
        val parent = mListPlayerContainer.parent
        if (parent is RelativeLayout) {
            (parent as ViewGroup).removeView(mListPlayerContainer)
            mVideoListPlayer.stop()
            mVideoListPlayer.setSurface(null)
        } else {

        }
        val containerView = mAdapter.getViewByPosition(position, R.id.rlItemDyOuter) as ViewGroup
        containerView.addView(mListPlayerContainer, 0)
        //防止退出后台之后，再次调用start方法，导致视频播放
        if (!mIsOnBackground) {
            //开始播放视频
            mVideoListPlayer.moveTo(position.toString() + "")
        }
    }

    /**
     * 停止视频播放
     */
    private fun stopPlay() {
        val parent = mListPlayerContainer.parent
        if (parent is RelativeLayout) {
            parent.removeView(mListPlayerContainer)
        }
        mVideoListPlayer.stop()
        mVideoListPlayer.setSurface(null)
        //视频第一帧开始渲染。此时可以隐藏封面
        val ivPic = mAdapter.getViewByPosition(mCurrentPosition, R.id.ivItemDyPic)
        ivPic?.visibility = View.VISIBLE
    }


    /**
     * 初始化播放View 关键代码，好好理解！！
     */
    lateinit var mListPlayerContainer: View
    lateinit var mPlayIconImageView: ImageView
    lateinit var mListPlayerTextureView: TextureView

    @SuppressLint("ClickableViewAccessibility")
    private fun initPlayerView() {
        mListPlayerContainer = View.inflate(this, R.layout.layout_list_player_view, null)
        mPlayIconImageView = mListPlayerContainer.findViewById(R.id.iv_play_icon)
        mListPlayerTextureView = mListPlayerContainer.findViewById(R.id.list_player_textureview)

        //TextureView
        mListPlayerTextureView.surfaceTextureListener = object : SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                surfaceTexture: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                val mSurface = Surface(surfaceTexture)
                mVideoListPlayer.setSurface(mSurface)
                mVideoListPlayer.redraw()
            }

            override fun onSurfaceTextureSizeChanged(
                surface: SurfaceTexture,
                width: Int,
                height: Int
            ) {
                mVideoListPlayer.redraw()
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                //这里一定要return false。这样SurfaceTexture不会被系统销毁
                //测试发现 返回 true 也没有什么影响,官方demo 中是返回的true
                return false
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
                //System.out.println("initPlayerView AliListPlayerActivity.onSurfaceTextureUpdated");
            }
        }

        //手势监听器
        mGestureDetector = GestureDetector(this, object : SimpleOnGestureListener() {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                onPauseClick()
                return true
            }

            override fun onDown(e: MotionEvent): Boolean {
                return true
            }
        })

        //播放列表界面的touch事件由手势监听器处理
        mListPlayerContainer.setOnTouchListener(OnTouchListener { view, motionEvent ->
            mGestureDetector.onTouchEvent(
                motionEvent
            )
        })
    }


    /**
     * 视频暂停/恢复的时候使用，
     */
    fun onPauseClick() {
        if (mIsPause) {
            resumePlay()
        } else {
            pausePlay()
        }
    }

    /**
     * 暂停播放
     */
    private fun pausePlay() {
        mIsPause = true
        mPlayIconImageView.visibility = View.VISIBLE
        mVideoListPlayer.pause()
    }

    /**
     * 恢复播放
     */
    private fun resumePlay() {
        mIsPause = false
        mPlayIconImageView.visibility = View.GONE
        mVideoListPlayer.start()
    }

    /**
     * 销毁
     */
    fun destroy() {
        mVideoListPlayer.stop()
        mVideoListPlayer.release()
    }

    /**
     * activity不可见或者播放页面不可见时调用该方法
     */
    fun setOnBackground(isOnBackground: Boolean) {
        mIsOnBackground = isOnBackground
        if (isOnBackground) {
            pausePlay()
        } else {
            resumePlay()
        }
    }

    private fun initAliPlayer() {
        mVideoListPlayer = AliPlayerFactory.createAliListPlayer(this)
        //开启硬解
        mVideoListPlayer.enableHardwareDecoder(true)
        //设置播放器参数
        val config: PlayerConfig = mVideoListPlayer.config
        //停止之后清空画面。防止画面残留（建议设置）
        config.mClearFrameWhenStop = true
        mVideoListPlayer.config = config
        //开启循环播放。短视频一般都是循环播放的
        mVideoListPlayer.isLoop = true
        //开启自动播放。
        mVideoListPlayer.isAutoPlay = true //注意这个一定要开启
        //设置预加载个数。此时会加载3个视频。当前播放的，和上下1个。
        mVideoListPlayer.setPreloadCount(1)
        //设置背景
        mVideoListPlayer.setVideoBackgroundColor(Color.TRANSPARENT)
        mVideoListPlayer.setOnPreparedListener(IPlayer.OnPreparedListener {
            //System.out.println("AliListPlayerActivity.onPrepared mIsPause=" + mIsPause + " mIsOnBackground=" + mIsOnBackground);
            if (!mIsPause && !mIsOnBackground) {
                mVideoListPlayer.start()
            }
        })
        //列表播放时一般都会有个封面，视频播起来之后，把封面隐藏，显示视频。
        mVideoListPlayer.setOnRenderingStartListener(OnRenderingStartListener {
            //视频第一帧开始渲染。此时可以隐藏封面
            val ivPic = mAdapter.getViewByPosition(mCurrentPosition, R.id.ivItemDyPic)
            ivPic?.visibility = View.GONE
        })
        mVideoListPlayer.setOnInfoListener(IPlayer.OnInfoListener {
            //播放时监听
        })
        mVideoListPlayer.setOnErrorListener(IPlayer.OnErrorListener { errorInfo ->
            Toast.makeText(this, "错误原因: $errorInfo", Toast.LENGTH_SHORT).show()
        })
    }

    override fun onResume() {
        super.onResume()
        setOnBackground(false)
    }


    override fun onPause() {
        super.onPause()
        setOnBackground(true)
    }


    override fun onDestroy() {
        super.onDestroy()
        destroy()
    }


}



